<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #percent {
            width: 300px;
            height: 20px;
            margin: 15px 0;
            background-color: pink;
        }

        #percent .inner {
            width: 0;
            height: 100%;
            background-color: skyblue;
            text-align: center;
        }
    </style>
</head>

<body>
    <input type="file" id="file1"><button id="upload">上传</button>
    <div id="percent">
        <div class="inner"></div>
    </div>
    <div id="preview"></div>
</body>
<script>
    // 获取元素
    const upload = document.querySelector('#upload');
    const file1 = document.querySelector('#file1');
    const preview = document.querySelector('#preview');
    const percent = document.querySelector('#percent .inner');

    // 原生上传
    upload.onclick = function () {
        if (file1.files.length === 0) return alert('请选择文件');
        let fd = new FormData();
        fd.append('avatar', file1.files[0]);

        const xhr = new XMLHttpRequest();

        // 上传进度
        xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                let complete = Math.ceil(e.loaded / e.total * 100);
                console.log(complete);
                percent.style.cssText = `width:${complete}%;backgroundColor:skyblue;`;
                percent.innerHTML = `${complete}%`;
            }
        }
        // 上传完成
        xhr.upload.onload = function () {
            percent.style.cssText = 'width:100%;color:white;';
            percent.innerHTML = `100%`;
        }

        xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
        xhr.send(fd);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = JSON.parse(xhr.responseText);
                if (res.status !== 200) return alert(res.msg);
                preview.innerHTML = `<img src="http://www.liulongbin.top:3006${res.url}" />`;
            }
        }
    }
</script>

</html>